package com.cictec.middleware.gps.engine.service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.feign.distribute.SendPlatformMessageToTerminalService;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.BusInstanceEngine;


/**
 * 【实时调度】前后车距
 * 
 * @author Administrator
 *
 */
@Service
public class StationNumberService {

	private static Logger logger = LoggerFactory.getLogger(StationNumberService.class);

	@Autowired
	private BusInstanceEngine busInstanceEngine;
	@Autowired
	private SendPlatformMessageToTerminalService sendPlatformMessageToTerminalService;

	/**
	 * 发送指定车辆的前后车距
	 * @param lineBus
	 * @param busUuid
	 */
	public void sendBeforeAfterStationNumber(String lineUuid, String lineType, String busUuid){
		
		List<BusInstance> lineBus = busInstanceEngine.getBusInstanceByLine(lineUuid, lineType);
		
		getSort(lineBus);
		String seqBus = null;
		for (BusInstance busInstance : lineBus) {
			seqBus = seqBus == null ? busInstance.getBusNumber() + "【" + busInstance.getStationSeq() + "】" + "【" + busInstance.getPositionRate() + "】"
					: seqBus + "," + busInstance.getBusNumber() + "【" + busInstance.getStationSeq() + "】" + "【" + busInstance.getPositionRate() + "】";
		}
		logger.debug("【前后车距】总计{}辆车，车辆排序：{}", lineBus.size(), seqBus);
		
		try {
			sendFrontBackComment(lineBus, busUuid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void getSort(List<BusInstance> lineBus){
		lineBus.sort(new Comparator<BusInstance>() {
			@Override
			public int compare(BusInstance o1, BusInstance o2) {
				
				String seq1 = PMSUtils.isNull(o1.getStationSeq());
				String seq2 = PMSUtils.isNull(o2.getStationSeq());
				
				int result = 0;
				if(!PMSUtils.isEmpty(seq1) && !PMSUtils.isEmpty(seq2)){
					
					// 正序排列
					double d = Integer.parseInt(seq1) - Integer.parseInt(seq2);
					result = (int)d;
				}
				return result;
			}
		});
		
		lineBus.sort(new Comparator<BusInstance>() {
			@Override
			public int compare(BusInstance o1, BusInstance o2) {
				
				String rate1 = PMSUtils.isNull(o1.getPositionRate());
				String rate2 = PMSUtils.isNull(o2.getPositionRate());
				
				int result = 0;
				if(!PMSUtils.isEmpty(rate1) && !PMSUtils.isEmpty(rate2)){
					
					// 正序排列
					double d = Double.parseDouble(rate1)*10000 - Double.parseDouble(rate2)*10000;
					result = (int)d;
				}
				return result;
			}
		});
	}
	
	private void sendFrontBackComment(List<BusInstance> lineBus, String busUuid){
		int count = lineBus.size();
		for (int i = 0; i < count; i++) {
			BusInstance current = lineBus.get(i);
			
			if(current.getBusUuid().equals(busUuid)){
				String devCode = current.getDevCode();
				String lineId = current.getDevLineId();
				
				if(i == 0){
					// 第一辆车
					BusInstance font = lineBus.get(i + 1);
					int fontSeq = Integer.parseInt(font.getStationSeq());
					int currentSeq = Integer.parseInt(current.getStationSeq());

					String content = sendCommand(devCode, lineId, fontSeq, currentSeq, null);
					logger.debug("【前后车距】：车辆 {} {},  前车:{}, 后车:没有", current.getBusNumber(), content, font.getBusNumber());
					
				}else if(i == count -1){
					// 最后一辆车
					BusInstance back = lineBus.get(i - 1);
					int currentSeq = Integer.parseInt(current.getStationSeq());
					int backSeq = Integer.parseInt(back.getStationSeq());

					String content = sendCommand(devCode, lineId, null, currentSeq, backSeq);
					logger.debug("【前后车距】：车辆 {} {},  前车:没有, 后车:{}", current.getBusNumber(), content, back.getBusNumber());
					
				}else{
					// 中间车辆
					BusInstance font = lineBus.get(i + 1);
					BusInstance back = lineBus.get(i - 1);
					int fontSeq = Integer.parseInt(font.getStationSeq());
					int currentSeq = Integer.parseInt(current.getStationSeq());
					int backSeq = Integer.parseInt(back.getStationSeq());
					
					String content = sendCommand(devCode, lineId, fontSeq, currentSeq, backSeq);
					logger.debug("【前后车距】：车辆 {} {}, 前车:{}, 后车:{}", current.getBusNumber(), content, font.getBusNumber(), back.getBusNumber());
				}
			}
		}
	}
	
	private String sendCommand(String devCode, String lineId, Integer font, Integer current, Integer back){
		
		int frontStationNumber = 0;
		int backStationNumber = 0;
		if(font != null){
			frontStationNumber = font - current;
			frontStationNumber = frontStationNumber < 0 ? 0 : frontStationNumber;
		}
		if(back != null){
			backStationNumber = current - back;
			backStationNumber = backStationNumber < 0 ? 0 : backStationNumber;
		}
		
		
		String content = "前后车距:" + (frontStationNumber == 0 ? "-" : frontStationNumber) + "/" + (backStationNumber == 0 ? "-" : backStationNumber);
		seandFontAndBackStationNumberCommand(devCode, lineId, content);
		
		return content;
		
	}
	
	private void seandFontAndBackStationNumberCommand(String devCode, String lineId, String content) {
//		logger.debug("【前后车距】：车辆 {} {}", busInstance.getBusNumber(), content);
		sendPlatformMessageToTerminalService.sendBeforAfterDistanceMessage(devCode, lineId, content);
	}
	
	public void checkFrontRearStationNumber() {
		logger.debug("【前后车距】计算");
		
		Map<String, List<BusInstance>> linesBus = busInstanceEngine.getBusInline();

		for (String lineUuidType : linesBus.keySet()) {

			List<BusInstance> lineBus = linesBus.get(lineUuidType);
			synchronized (lineBus) {

				if (lineBus.size() <= 1) {
					// 该线路没有车了直接跳过
					continue;
				}
				
				getSort(lineBus);

				String seqBus = null;
				for (BusInstance busInstance : lineBus) {
					seqBus = seqBus == null ? busInstance.getBusNumber() + "【" + busInstance.getStationSeq() + "】" + "【" + busInstance.getPositionRate() + "】"
							: seqBus + "," + busInstance.getBusNumber() + "【" + busInstance.getStationSeq() + "】" + "【" + busInstance.getPositionRate() + "】";
				}
				logger.debug("【前后车距】总计{}辆车，车辆排序：{}", lineBus.size(), seqBus);

				
				// 这里按照站序 从小到大
				BusInstance current = null;
				for (int i = 0; i < lineBus.size(); i++) {
					if (i == 0) {
						// 第一辆车
						current = lineBus.get(i);
						BusInstance font = lineBus.get(i + 1);
						String currentSeq = current.getStationSeq();
						String fontSeq = font.getStationSeq();

						int frontStationNumber = Integer.parseInt(fontSeq) - Integer.parseInt(currentSeq);
						frontStationNumber = frontStationNumber < 0 ? 0 : frontStationNumber;
						int backStationNumber = 0;

						String content = "前后车距:" + frontStationNumber + "/-";
						logger.debug("【前后车距】：车辆 {} {},  前车:{}, 后车:没有", current.getBusNumber(), content, font.getBusNumber());
						sendFontAndBackStationNumberCommand(current, frontStationNumber, backStationNumber);

					} else if (i == lineBus.size() - 1) {
						// 最后一辆车
						current = lineBus.get(i);
						BusInstance back = lineBus.get(i - 1);
						String currentSeq = current.getStationSeq();
						String backSeq = back.getStationSeq();

						int frontStationNumber = 0;
						int backStationNumber = Integer.parseInt(currentSeq) - Integer.parseInt(backSeq);
						backStationNumber = backStationNumber < 0 ? 0 : backStationNumber;

						String content = "前后车距:-/"+backStationNumber;
						logger.debug("【前后车距】：车辆 {} {},  前车:没有, 后车:{}", current.getBusNumber(), content, back.getBusNumber());
						sendFontAndBackStationNumberCommand(current, frontStationNumber, backStationNumber);

					} else {
						current = lineBus.get(i);
						BusInstance font = lineBus.get(i + 1);
						BusInstance back = lineBus.get(i - 1);
						String fontSeq = font.getStationSeq();
						String currentSeq = current.getStationSeq();
						String backSeq = back.getStationSeq();

						int frontStationNumber = 0;
						int backStationNumber = 0;
						try {
							frontStationNumber = Integer.parseInt(fontSeq) - Integer.parseInt(currentSeq);
							backStationNumber = Integer.parseInt(currentSeq) - Integer.parseInt(backSeq);
							
							frontStationNumber = frontStationNumber < 0 ? 0 : frontStationNumber;
							backStationNumber = backStationNumber < 0 ? 0 : backStationNumber;
							
							String content = "前后车距:" +frontStationNumber + "/" + backStationNumber;
							logger.debug("【前后车距】：车辆 {} {}, 前车:{}, 后车:{}", current.getBusNumber(), content, font.getBusNumber(), back.getBusNumber());
						} catch (NumberFormatException e) {
						}
						sendFontAndBackStationNumberCommand(current, frontStationNumber, backStationNumber);

					}
				}
			}
		}

		// 不在线了上的车 前后车距设置为 -/-
		List<BusInstance> list= busInstanceEngine.getAllBusInstance(true);
		String notInline = "";
		for (BusInstance busInstance : list) {
			
			if(busInstance.isInStandBy() 
					|| busInstance.isInDeviate()
					|| busInstance.isInPark()
					){
				
				notInline = PMSUtils.isEmpty(notInline) ? busInstance.getBusNumber() : notInline + ", " + busInstance.getBusNumber();
				sendFontAndBackStationNumberCommand(busInstance, 0, 0);
			}
		}
		logger.debug("不再线路的车辆：前后车距设置为 -/-,{}", notInline);
		
		// 测试代码
		// BusInstance busInstance = busInstanceEngine.getBusInstanceByDevCode("54849");
		// seandFontAndBackStationNumberCommand(busInstance, 0, 5);
	};
	
	

	/**
	 * 前后车距
	 * 
	 * @param busInstance
	 * @param fontNumber
	 * @param backNumber
	 */
	private void sendFontAndBackStationNumberCommand(BusInstance busInstance, int fontNumber, int backNumber) {

		String content = "前后车距:" + (fontNumber == 0 ? "-" : fontNumber) + "/" + (backNumber == 0 ? "-" : backNumber);

//		logger.debug("【前后车距】：车辆 {} {}", busInstance.getBusNumber(), content);

		String devCode = busInstance.getDevCode();
		String lineId = busInstance.getDevLineId();
		seandFontAndBackStationNumberCommand(devCode, lineId, content);
	}

}
